<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Storage;
use Event;
use App\Events\debug\Debug;
use App\Events\log\AllLog;
use App\Events\noti\Inform;
use App\Models\Area;
use App\Models\Building;
use App\Models\Room;
use Cache;

class NBSecurityController extends Controller
{
	//安防应用报警接收接口
	public function index(Request $request)
    {
        /*$info = $request -> all();
        Storage::disk('local')->put('file.txt', json_encode($info));*/
        $info = '{
            "notifyType":"deviceDatasChanged",
            "deviceId":"3aa14814-24c2-456d-befe-86b1de3c1b30",
            "gatewayId":"3aa14814-24c2-456d-befe-86b1de3c1b30",
            "services":[{
                "serviceId":"Infrared",
                "serviceType":"Infrared",
                "data":{
                    "Infrared_alarm":"1",
                    "Infrared_battery":"0",
                    "Infrared_apart":"0",
                    "Base_apart":"0",
                    "Base_lost":"0",
                    "Base_temperature":"0",
                    "Base_battery":"0",
                    "Base_Other":"0"
                    },
            "eventTime":"20180702T040416Z"
            }]
        }';
        $info = json_decode($info,true);
        $where = array();
        $where['nd.deviceId'] = $info['deviceId'];
        //查询qy_smoke表,获取设备信息
        $msg = DB::table('nb_bind as nb')
            -> leftJoin('storage as s','s.id','=','nb.storage_id')
            -> leftJoin('nb_device as nd','nd.id','=','nb.device_id')
            -> leftJoin('room as r','nb.room_id','=','r.id')
            -> leftJoin('area as a','r.area_id','=','a.id')
            -> leftJoin('camera as c','nb.camera_id','=','c.id')
            -> select('nb.agent_id','s.num as num','nd.verifyCode as verifyCode','nb.status','nb.room_id','nb.loc','r.name as rname','r.latitude','r.longitude','r.area_id','a.name as aname','c.url')
            -> where($where)
            -> first();
        //设备类型
        $devType = $info['services'][0]['serviceType'];
        switch ($devType) {
            case 'Infrared':
                $msg['type'] = '红外';
                break;

            default:
                $msg['type'] = '其他';
                break;
        }
        //报警类型
        $warning = array_search(1,$info['services'][0]['data']);
        if($warning){
            switch ($warning) {
                case 'Infrared_alarm':
                    $msg['genre'] = '红外';
                    break;
                case 'Infrared_battery':
                    $msg['genre'] = '欠压';
                    break;
                case 'Infrared_apart':
                    $msg['genre'] = '防拆';
                    break;
                case 'Base_apart':
                    $msg['genre'] = '底座防拆';
                    break;
                case 'Base_lost':
                    $msg['genre'] = '底座失联';
                    break;
                case 'Base_temperature':
                    $msg['genre'] = '底座温度';
                    break;
                case 'Base_battery':
                    $msg['genre'] = '底座电量';
                    break;
                default:
                    $msg['genre'] = '底座其他';
                    break;
            }

            //用户信息
            $users = array();
            $busers = array();
            $wechat = array();
            $users['bemail'] = array();
            $users['bphone'] = array();
            $users['bmobile'] = array();
            $noti = DB::table('noti_set')->get();
            // 获取用户信息
            // $area = Area::where('id',$msg['area_id'])->first()->member()->orderBy('name')->get();
            $area = Area::where('id',$msg['area_id']) -> first();
            if ( (!empty($area)) && (!empty($area->member)) ){
                foreach ($area->member as $areaUsers) {
                    if ($areaUsers->name) {
                        array_push($busers,$areaUsers->name);
                    }
                    // 邮箱
                    if (($noti['2']['noti_area']==1)&&($areaUsers->email)) {
                        array_push($users['bemail'],$areaUsers->email);
                    }
                    // 短信
                    if (($noti['0']['noti_area']==1)&&($areaUsers->phone)) {
                        array_push($users['bphone'],$areaUsers->phone);
                    }
                    // 语音
                    if (($noti['1']['noti_area']==1)&&($areaUsers->phone)) {
                        array_push($users['bmobile'],$areaUsers->phone);
                    }
                    //微信
                    if ($areaUsers->wechat_openid) {
                        array_push($wechat,$areaUsers->wechat_openid);
                    }
                }
            }
            $ausers = implode($busers);
            $room = Room::where('id',$msg['room_id'])->first();
            if( (!empty($room)) && (!empty($room->member)) ) {
                foreach ($room->member as $roomUsers) {
                    if ($roomUsers->name) {
                        array_push($busers,$roomUsers->name);
                    }
                    // 邮件
                    if (($noti['2']['noti_room']==1)&&($roomUsers->email)) {
                        array_push($users['bemail'],$roomUsers->email);
                    }
                    // 短信
                    if (($noti['0']['noti_room']==1)&&($roomUsers->phone)) {
                        array_push($users['bphone'],$roomUsers->phone);
                    }
                    // 语音
                    if (($noti['1']['noti_room']==1)&&($roomUsers->phone)) {
                        array_push($users['bmobile'],$roomUsers->phone);
                    }
                    //微信
                    if ($roomUsers->wechat_openid) {
                        array_push($wechat,$roomUsers->wechat_openid);
                    }
                }
            }
            $time = time();
            $msg['time'] = $time;
            // workerman
            $msg['user'] = array_pop($busers);
            $userphone = $users['bphone'];
            // $msgdata['phone'] = substr_replace(array_pop($userphone),"****",3,4);
            $msg['phone'] = array_pop($userphone);
            $data_json = json_encode($msg);
            unset($msg['user'],$msg['phone']);
            // 指明给谁推送，为空表示向所有在线用户推送
            $to_uid = "af";
            // 推送的url地址，使用自己的服务器地址
            $push_api_url = "http://af.iqykj.com:2121/";
            $post_data = array(
                "type" => "publish",
                "content" => $data_json,
                "to" => $to_uid,
            );
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_URL, $push_api_url );
            curl_setopt ( $ch, CURLOPT_POST, 1 );
            curl_setopt ( $ch, CURLOPT_HEADER, 0 );
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
            curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
            $return = curl_exec ( $ch );
            curl_close ( $ch );
            var_export($return);

            // 通知
            Event::fire(new Inform($msg,$users,$noti));

            //将原始数据写入数据库
            $raw = $info['services'][0]['data'];
            $raw['deviceId'] = $info['deviceId'];
            DB::table('profile_'.strtolower($info['services'][0]['serviceType']))
                -> insert($raw);
            if($msg['agent_id'] == 1){
                //写入运营报表
                $info_id = DB::table('nb_report') -> insertGetId(['num'=>$msg['num'],'verifyCode'=>$msg['verifyCode'],'type_name'=>$msg['type'],'area_id'=>$msg['area_id'],'room_id'=>$msg['room_id'],'loc'=>$msg['loc'],'genre'=>$msg['genre'],'addTime'=>$time,'agent_id'=>$msg['agent_id'],'staffs'=>$ausers]);
                //微信通知商户
                $wechat_data['url'] = "";
                $wechat_data['first'] = $msg['type'].'探测器';
                $wechat_data['keyword1'] = $msg['genre'];
                $wechat_data['keyword2'] = $msg['num'].'号设备';
                // $wechat_data['remark'] = '尊敬的用户，您位于'.$info['name']."的".substr($MsgCont,3).'，请您及时检查并处置！';
                $wechat_data['remark'] = "尊敬的用户：\r\n       您位于".$msg['aname'].$msg['rname']."的设备发生".$msg['genre']."告警！！";
                foreach ($wechat as $k => $v) {
                    $wechat_msg = WechatController::wechat_pushmsg($v,$wechat_data);
                }
                $wechat_msg = json_decode($wechat_msg,true);
                if($wechat_msg['errmsg'] == "ok"){
                    $bool = true;
                }else{
                    $bool = false;
                }

                //查询派警表
                $res = DB::table('paijing') -> where(['room_id'=>$msg['room_id'],'status'=>0]) -> select('id') -> first();
                if($res){
                    //将派警id修改到消息报表中
                    DB::table('nb_report') -> where('id',$info_id) -> update(['paijing_id'=>$res['id']]);
                }else{
                    //没有查到，插入一条派警工单
                    $paijing_id = DB::table('paijing') -> insertGetId(['num'=>'pj'.$time.rand(1000,9999),'room_id'=>$msg['room_id'],'add_time'=>$time]);
                    DB::table('nb_report') -> where('id',$info_id) -> update(['paijing_id'=>$paijing_id]);
                    //微信通知接警
                            $wechat_data['url'] = "http://wap.iqykj.com/oa/oapaijing/index";
                            $wechat_data['first'] = $msg['type'].'探测器';
                            $wechat_data['keyword1'] = $msg['genre'];
                            $wechat_data['keyword2'] = $msg['num'].'号设备';
                            // $wechat_data['remark'] = '尊敬的用户，您位于'.$info['name']."的".substr($MsgCont,3).'，请您及时检查并处置！';
                            $wechat_data['remark'] = "您好：\r\n       位于".$msg['aname'].$msg['rname']."的设备发生".$msg['genre']."告警！请速去处理！";
                    foreach ($wechat as $k => $v) {
                       $wechat_msg = WechatController::wechat_pushmsg($v,$wechat_data);
                    }
                    $wechat_msg = json_decode($wechat_msg,true);
                            if($wechat_msg['errmsg'] == "ok"){
                                $bool = true;
                            }else{
                                $bool = false;
                            }

                }
            }
        }
    }
}